package com.gexin.model.product;

import com.gexin.common.cache.CacheUtils;
import com.gexin.common.utils.SQLUtils;
import com.gexin.common.utils.StringUtil;
import com.gexin.model.activity.GroupRule;
import com.gexin.model.activity.ReverseMultipleRule;
import com.gexin.model.product.base.BaseProducts;
import com.gexin.plugin.sqlinxml.SqlKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

import java.math.BigDecimal;
import java.util.*;

import org.apache.commons.lang3.StringUtils;

import static com.gexin.common.utils.ArithUtil.percent;
import static com.gexin.common.utils.ArithUtil.percentt;

public class Products
		extends BaseProducts<Products>
{
	public static final Products dao = new Products();
	private static String cache_App_Product_Detail = "cache:app:product:";
	public static final Integer examine_state0 = Integer.valueOf(0);
	public static final Integer examine_state1 = Integer.valueOf(1);
	public static final Integer examine_state2 = Integer.valueOf(2);



	public void cache_ClearProductData()
	{
		CacheUtils.del(cache_App_Product_Detail + getId());
	}

	public List<Products> getProducts(){
		List<Products> productsList=Products.dao.find("select * from t_products");
		return productsList;
	}
	public static Boolean insertReverseMultipleRule(String reverse_multiple_min, String reverse_multiple_max, String reverse_multiple_count_min, String reverse_multiple_count_max) {
		ReverseMultipleRule reverseMultipleRule = new ReverseMultipleRule();
		BigDecimal reverseMultipleMin= BigDecimal.valueOf(percent(Integer.parseInt(reverse_multiple_min),100));
		BigDecimal reverseMultipleMax= BigDecimal.valueOf(percent(Integer.parseInt(reverse_multiple_max),100));
		BigDecimal reverseMultipleCountMin= BigDecimal.valueOf(percentt(Double.parseDouble(reverse_multiple_count_min),1));
		BigDecimal reverseMultipleCountMax= BigDecimal.valueOf(percentt(Double.parseDouble(reverse_multiple_count_max),1));
		reverseMultipleRule.setId(UUID.randomUUID().toString());
		reverseMultipleRule.setReverseMultipleMin(reverseMultipleMin);
		reverseMultipleRule.setReverseMultipleMax(reverseMultipleMax);
		reverseMultipleRule.setReverseMultipleCountMin(reverseMultipleCountMin);
		reverseMultipleRule.setReverseMultipleCountMax(reverseMultipleCountMax);
		reverseMultipleRule.setStatus(1);
		long time = new Date().getTime();
		reverseMultipleRule.setCreateTime(time);
		reverseMultipleRule.setUpdateTime(time);
		Boolean flag = false;
		flag = reverseMultipleRule.save();
		return flag;
	}
	public static Boolean deletProducts(String id){
		return Products.dao.deleteById(id);
	}
	public Map<String, Object> getProductsDetailByID(Integer product_id)
	{
		Map<String, Object> map = new HashMap();
		map = new HashMap();
		Products product = dao.getGroupProductById(product_id);
		if (product == null) {
			return null;
		}
		map.put("product_name", product.getProductName());
		map.put("banner", product.getImageBanner().split(","));
		map.put("product", product);
		map.put("stock_text", ProductSku.dao.cache_getStockByProduct(product_id.intValue()));
		return map;
	}

	public List<Products> getProductByChannel(String typeId, String sort, String sort_index, Integer page)
	{
		SQLUtils sql = new SQLUtils("select id, product_name,image_center,channel_money,group_price,sale_count from t_products where online_state=1 and del_state=0  and channel_money>0.0 ");
		if (!StringUtil.show(typeId).equals("all")) {
			if (StringUtil.show(typeId).equals("hot")) {
				sql.whereEquals("lable_css", "pro");
			} else {
				sql.whereEquals("type_id", typeId);
			}
		}
		sql.append(String.format(" order by %s  %s", new Object[] { sort, sort_index }));
		sql.append(" LIMIT ?,10");

		return dao.find(sql.toString(), new Object[] { Integer.valueOf(page.intValue() * 10) });
	}

	public List<Products> getAllProductsByShop_id(String shop_id)
	{
		List<Products> list = null;
		list = dao.find("select  id,product_name from t_products where del_state=0  and shop_id=? order by sort desc", new Object[] { shop_id });
		return list;
	}

	public List<Products> getAllProducts()
	{
		List<Products> list = null;
		list = dao.find("select  id,product_name from t_products where del_state=0  order by sort desc");
		return list;
	}

	public String[] getDetailImg()
	{
		if (getImageDetail() != null) {
			return getImageDetail().split(",");
		}
		return null;
	}

	public Products getProductBaseById(Integer id)
	{
		return (Products)findByIdLoadColumns(id, "buy_count_post_fee,extend_type,source_is_auto,source_sku_id,free_group_state,free_group_person,stock_count,attr_type,id,shop_id,product_name,online_state,image_center,price,post_fee,template_id,group_person,group_price,channel_money,second_price,second_num,second_order_num,full_free_post_fee,restrictions_buy_num,first_discount_price,is_overseas_purchasing,preordain_front_money,preordain_tail_money,preordain_start_time,preordain_end_time,preordain_state,tail_pay_time,buy_quota,del_state,sale_count");
	}

	public Page<Products> paginate(Products obj, int pageNumber, int pageSize)
	{
		SQLUtils sql = new SQLUtils(" from t_products pro  left join t_product_type  t  on pro.type_id=t.id  left join t_shop_info s  on s.shop_id=pro.shop_id  where   pro.del_state!=1 ");
		if (obj != null)
		{
			if (obj.getTypeId() != null) {
				sql.whereEquals("type_id", obj.getTypeId());
			}
			if (StringUtil.isNotBlank(obj.getProductName())) {
				sql.whereLike("product_name", obj.getProductName());
			}
			if (obj.getShopId() != null) {
				sql.whereEquals("pro.shop_id", obj.getShopId());
			}
			if (obj.getOnlineState() != null) {
				sql.whereEquals("online_state", obj.getOnlineState());
			}
		}
		sql.append(" order by createtime desc");
		return dao.paginate(pageNumber, pageSize, "select pro.*,t.type_name,s.shop_name", sql.toString());
	}

	public Page<Products> paginate(String shop_id, Products obj, int pageNumber, int pageSize)
	{
		SQLUtils sql = new SQLUtils(" from t_products pro   where  pro.del_state!=1");
		if (obj != null)
		{
			if (obj.getTypeId() != null) {
				sql.whereEquals("type_id", obj.getTypeId());
			}
			if (obj.getOnlineState() != null) {
				sql.whereEquals("online_state", obj.getOnlineState());
			}
			if (obj.getSupplyType() != null) {
				sql.whereEquals("supply_type", obj.getSupplyType());
			}
			if (StringUtil.isNotBlank(obj.getProductName())) {
				sql.whereLike("product_name", obj.getProductName());
			}
			if ((obj.getAttrType() != null) && (obj.getAttrType().intValue() != 0)) {
				sql.whereEquals("attr_type", obj.getAttrType());
			}
		}
		sql.append(" and pro.shop_id = ?");
		sql.append(" order by online_state,createtime desc");
		return dao.paginate(pageNumber, pageSize, "select pro.*", sql.toString(), new Object[] { shop_id });
	}

	public int addSaleCount(Integer id)
	{
		return Db.update("update t_products set sale_count=sale_count+1,stock_count=stock_count-1 where id=?", new Object[] { id });
	}

	public List<Products> getProductsByType(String type_id)
	{
		List<Products> list = null;
		String sql = "select  * from t_products where del_state=0 and type_id= " + type_id;
		sql = sql + " order by sort desc";
		list = dao.find(sql);
		return list;
	}

	public List<Products> getProductsByAttrType(Integer attr_type)
	{
		List<Products> list = null;
		String sql = "select  * from t_products where del_state=0 and online_state=1 and attr_type= " + attr_type;
		if (attr_type.intValue() == 2) {
			sql = sql + " and preordain_state = 1";
		}
		sql = sql + " order by sort desc";
		list = dao.find(sql);
		return list;
	}

	public List<Products> getProductsByAttrType(Integer attr_type, Integer type_sub_one_id, String title)
	{
		List<Products> list = null;
		String sql = "select  id,attr_type,product_name,image_center,integral from t_products where del_state=0 and online_state=1 and examine_state=1 and attr_type= " + attr_type;
		if (!StringUtils.isEmpty(title)) {
			sql = sql + " and product_name like '%" + title + "%' ";
		}
		sql = sql + " and type_sub_one_id = " + type_sub_one_id;
		sql = sql + " order by sort desc";
		list = dao.find(sql);
		return list;
	}

	public List<Products> getProductsByAgent(Integer type_sub_one_id, String title)
	{
		List<Products> list = null;
		String sql = "select  id,attr_type,product_name,image_center,price from t_products where del_state=0 and online_state=1 and examine_state=1 and attr_type=1 ";
		if (!StringUtils.isEmpty(title)) {
			sql = sql + " and product_name like '%" + title + "%' ";
		}
		sql = sql + " and type_sub_one_id = " + type_sub_one_id;
		sql = sql + " order by sort desc";
		list = dao.find(sql);
		return list;
	}

	public List<Products> cache_getProductIndex(String shopid)
	{
		List<Products> list = (List)CacheUtils.getEhcache("cache_ProductIndex" + shopid);
		if (list == null)
		{
			list = dao.find(SqlKit.sql("product.cache_getProductIndex"), new Object[] { shopid });
			CacheUtils.setEhcache("halfHour", "cache_ProductIndex" + shopid, list);
		}
		return list;
	}

	public Products cache_getProductDetail(Integer id)
	{
		Products pro = (Products)CacheUtils.get("cache:products:detail:" + id);
		if (pro == null)
		{
			pro = (Products)findByIdLoadColumns(id, "source_is_auto,source_sku_id,free_group_state,free_group_person,stock_count,attr_type,id,shop_id,product_name,online_state,image_center,price,post_fee,template_id,group_person,group_price,channel_money");
			if (pro != null) {
				CacheUtils.set("cache:products:detail:" + id, pro, 86400);
			}
		}
		return pro;
	}

	public void cache_clear()
	{
		CacheUtils.del("cache:products:detail:" + getId());
		CacheUtils.del("cache:products:sku2:" + getId());
		CacheUtils.del("cache:product:detail1:" + getId());
		CacheUtils.delEhcache("halfHour", "cache_ProductIndex");
	}

	public List<Products> getProductByTypeId(String typeId, String sort, String sort_index, Integer page)
	{
		SQLUtils sql = new SQLUtils("select id, product_name,image_center,price,market_price,lable_css from t_products where online_state=1 and del_state=0 ");
		if (!StringUtil.show(typeId).equals("all")) {
			if (StringUtil.show(typeId).equals("hot")) {
				sql.whereEquals("bargin_state", Integer.valueOf(1));
			} else {
				sql.whereEquals("type_id", typeId);
			}
		}
		sql.append(String.format(" order by %s  %s", new Object[] { sort, sort_index }));
		sql.append(" LIMIT ?,10");
		return dao.find(sql.toString(), new Object[] { Integer.valueOf(page.intValue() * 10) });
	}

	public List<Products> getProductByTagId(String tagId, String sort, String sort_index, Integer page)
	{
		SQLUtils sql = new SQLUtils("select p.id, p.product_name,p.image_center,p.price,p.market_price,p.lable_css from t_products_tag_rel t left join t_products p  on t.product_id=p.id where p.online_state=1 and p.del_state=0 ");
		if (StringUtil.isNotBlank(tagId)) {
			sql.whereEquals("t.tag_id", tagId);
		}
		sql.append(String.format(" order by %s  %s", new Object[] { "p." + sort, sort_index }));
		sql.append(" LIMIT ?,10");
		return dao.find(sql.toString(), new Object[] { Integer.valueOf(page.intValue() * 10) });
	}

	public Products getProductById(Integer id)
	{
		return (Products)findFirst(SqlKit.sql("product.getProductById"), new Object[] { id });
	}

	public Products getGroupProductById(Integer id)
	{
		return (Products)findById(id);
	}

	public List<Products> getProductlistByShopId(int page, String shop_id, int online_state, int supply_type)
	{
		SQLUtils sql = new SQLUtils("select * from t_products where del_state=0");
		sql.append(" and shop_id=? ");
		sql.append(" and online_state=? ");
		sql.append(" and supply_type=? ");
		sql.append(" order by createtime desc LIMIT ?,?");
		return dao.find(sql.toString(), new Object[] { shop_id, Integer.valueOf(online_state), Integer.valueOf(supply_type), Integer.valueOf(page * 10), Integer.valueOf(10) });
	}

	public Products getProductMsgById(String id)
	{
		String sql = " select * from t_products where id=? ";
		return (Products)dao.findFirst(sql, new Object[] { id });
	}

	public List<Products> getProductBytype(int page, int type_id, int online_state, int supply_type)
	{
		SQLUtils sql = new SQLUtils("select id,supply_type,product_name,online_state,price,stock_count,image_center from t_products where del_state=0 ");
		sql.whereEquals("type_id", Integer.valueOf(type_id));
		sql.append(" and online_state=? ");
		sql.append(" and supply_type=? ");
		sql.append(" order by createtime desc  limit ?,? ");
		return dao.find(sql.toString(), new Object[] { Integer.valueOf(online_state), Integer.valueOf(supply_type), Integer.valueOf(page * 10), Integer.valueOf(10) });
	}

	public Products getCountByTypeID(int type_id)
	{
		String sql = "select count(type_id) as count from t_products where del_state=0 and type_id=? ";
		return (Products)dao.findFirst(sql, new Object[] { Integer.valueOf(type_id) });
	}

	public List<Products> getProductByName(int page, String search, String shop_id)
	{
		SQLUtils sql = new SQLUtils("select * from t_products where del_state=0 ");
		sql.whereEquals("shop_id", shop_id);
		sql.whereLike("product_name", search);
		sql.append(" order by createtime desc Limit ?,? ");
		return dao.find(sql.toString(), new Object[] { Integer.valueOf(page * 10), Integer.valueOf(10) });
	}

	public List<Products> getNoTypeProduct(int page, String shop_id)
	{
		SQLUtils sql = new SQLUtils("select * from t_products where del_state=0 ");
		sql.whereEquals("shop_id", shop_id);
		sql.append(" and type_id is null");
		sql.append(" order by createtime desc  limit ?,10");
		return dao.find(sql.toString(), new Object[] { Integer.valueOf(page * 10) });
	}

	public Products getNoTypeCount(String shop_id)
	{
		String sql = "select count(id) as count from t_products where shop_id=? and del_state=0 and type_id is null ";
		return (Products)dao.findFirst(sql, new Object[] { shop_id });
	}

	public void addProductPv(int product_id)
	{
		String sql = " update t_products set product_pv=product_pv+1 where id=?";
		Db.update(sql, new Object[] { Integer.valueOf(product_id) });
	}

	public void addProductUv(int product_id)
	{
		String sql = " update t_products set product_uv=product_uv+1 where id=?";
		Db.update(sql, new Object[] { Integer.valueOf(product_id) });
	}

	public Long getOnlineNumberByShopId(String shop_id)
	{
		String sql = "  select count(*) from t_products where online_state=1 and shop_id=?   ";
		return Db.queryLong(sql, new Object[] { shop_id });
	}

	public Page<Products> time_paginate(Products product, String shop_id, int time_scope, String day, String start_time, String end_time, int pageNumber, int pageSize)
	{
		String select_sql = " select  d.product_id ,p.product_name,p.image_center,sum(d.product_pv) as pv ,sum(d.product_uv)  as uv,sum(d.pay_people_num)as pay_people_num ,sum(d.pay_num) as order_real ";
		SQLUtils sql = new SQLUtils(" from  t_products p    left join      t_data_everyday_product d   on  d.product_id=p.id    ");
		sql.append(" where p.shop_id= ? and p.online_state=1 ");
		if (time_scope == 1) {
			sql.append(" and DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(d.data_time) ");
		}
		if (time_scope == 2) {
			sql.append(" and DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(d.data_time) ");
		}
		if (time_scope == 3) {
			sql.append(" and  d.date_str ='" + day + "'");
		}
		if (time_scope == 4) {
			sql.append(" and d.data_time >= '" + start_time + "' and  d.data_time <= '" + end_time + "'");
		}
		sql.append(" group by  d.product_id ");
		return dao.paginate(pageNumber, pageSize, select_sql, sql.toString(), new Object[] { shop_id });
	}

	public Page<Products> paginate(Products product, String shop_id, String time_scope, int pageNumber, int pageSize)
	{
		String select_sql = "select   p.id,p.image_center,p.product_name,p.shop_id,  ifnull(c.pv,0) as pv  ,ifnull(e.uv,0) as uv ,ifnull(d.order_num,0) as order_num  ,ifnull(f.order_real,0) as order_real ,ifnull(g.pay_people_num,0)as pay_people_num ";
		String shop_sql = "  and p.shop_id= '" + shop_id + "' ";

		String today_sql = " date_format(a.createtime,'%Y-%m-%d')=date_format(now(),'%Y-%m-%d') ";

		String time_sql = "";
		time_sql = today_sql;
		String order_time_sql = " date_format(o.createtime,'%Y-%m-%d')=date_format(now(),'%Y-%m-%d') ";

		SQLUtils sql = new SQLUtils(" from t_products p    ");

		sql.append("  left join  (  select   a.product_id,count(*)  as pv  FROM  t_products b   left join t_data_view_product a on b.id=a.product_id ");
		sql.append(" where " + time_sql + " group by product_id )  c   on  c.product_id=p.id ");

		sql.append("   left join  (  select   a.product_id,count(distinct user_id)  as uv  FROM  t_products b   left join t_data_view_product a on b.id=a.product_id ");
		sql.append(" where " + time_sql + " group by product_id)  e  on  e.product_id=p.id ");

		sql.append(" left join  ( select i.product_id,sum(i.nums) as order_num from  t_order_item i  left join t_order o on o.id=i.order_id left join t_products b on b.id=i.product_id  ");
		sql.append(" where " + order_time_sql + " group by product_id    )  d on d.product_id=p.id ");

		sql.append(" left join  ( select i.product_id,sum(i.nums) as order_real from  t_order_item i  left join t_order o on o.id=i.order_id left join t_products b on b.id=i.product_id   ");
		sql.append(" where " + order_time_sql + " and o.pay_state=2  group by product_id    )  f  on f.product_id=p.id ");

		sql.append(" left join  ( select i.product_id,count(distinct user_id) as pay_people_num from  t_order_item i  left join t_order o on o.id=i.order_id left join t_products b on b.id=i.product_id   ");
		sql.append(" where " + order_time_sql + "and o.pay_state=2  group by product_id    )  g  on g.product_id=p.id ");

		sql = sql.append("   where 1=1 ");
		if (shop_id != null) {
			sql = sql.append(shop_sql);
		}
		if (product != null)
		{
			if (product.getProductName() != null) {
				sql.whereLike("p.product_name", product.getProductName());
			}
			if (product.getProductTag() != null) {
				sql.whereLike("p.product_tag", product.getProductTag());
			}
		}
		sql.append("  and p.online_state=1    order by uv desc ");
		return dao.paginate(pageNumber, pageSize, select_sql, sql.toString());
	}

	public List<Products> jifen_getProductlistByShopId(int page, String shop_id)
	{
		SQLUtils sql = new SQLUtils("select * from t_products where del_state=0");
		sql.append(" and shop_id=? ");
		sql.append(" and online_state=1 ");
		sql.append(" and jifen_buy_state=1 ");
		sql.append(" order by createtime desc LIMIT ?,?");
		return dao.find(sql.toString(), new Object[] { shop_id, Integer.valueOf(page * 10), Integer.valueOf(10) });
	}

	public List<Products> findRushBuyByState(Integer state)
	{
		SQLUtils sql = new SQLUtils(" select * from  t_products where attr_type = 5 and online_state = 1 ");
		if (state != null) {
			if (state.intValue() == 0) {
				sql.append(" and rush_buy_state=0 ");
			} else if (state.intValue() == 1) {
				sql.append(" and rush_buy_state in(1,2) ");
			} else if (state.intValue() == 3) {
				sql.append(" and rush_buy_state=3 ");
			}
		}
		sql.append(" order by rush_buy_state,rush_buy_start_time asc ");
		return dao.find(sql.toString());
	}

	public List<Products> getBestSeller()
	{
		return dao.find(" select * from t_products where online_state=1 order by sale_count desc limit 0,10 ");
	}

	public List<Products> findByAttrType(Integer type, Integer page)
	{
		return dao.find(" select * from t_products where online_state=1 and attr_type=? order by sale_count desc limit ?,10 ", new Object[] { type, page });
	}

	public List<Products> findByHotProduct()
	{
		return find("select  * from t_products where is_hot=1");
	}

	public List<Products> findByHotProduct(Integer attr_type)
	{
		return find("select  * from t_products where is_hot=1 and attr_type = ? and online_state=1 and examine_state=1  order by sort asc LIMIT 4 ", new Object[] { attr_type });
	}

	public List<Products> findNormalProductByType(Integer typeId)
	{
		return find("select * from t_products where type_id=? and  is_presell=0 and examine_state=1 ", new Object[] { typeId });
	}

	public List<Products> findPresellProductByType(Integer typeId)
	{
		return find("select * from t_products where type_id=? and  is_presell=1", new Object[] { typeId });
	}

	public Long findAgentSize(Integer id)
	{
		return Db.queryLong("select count(*) from t_products where online_state=1 and del_state=0  and attr_type = 1 ");
	}

	public List<Products> findNormalProductAll()
	{
		return find("select * from t_products where  attr_type=1");
	}

	public Products findRegisterProduct()
	{
		return (Products)findFirst("select * from t_products where  attr_type=6");
	}
}
